package com.chengzhi.structure;


/**
 * @description: 单向链表
 * @author: ruanchengzhi
 * @create: 2020-08-20 09:52
 **/
public class LinkedList<E> implements BaseLinkedList<E> {

    private Node<E> head;

    private int size;

    public LinkedList() {
        this.size = 0;
    }

    @Override
    public void add(int index, E value) {
        if (index < 0 || index > size) {
            throw new IndexOutOfBoundsException("index > size");
        }
        Node<E> node = new Node<>(value);
        int length = 1;
        Node root = head;
        while (null != root.next) {
            if (index == length++) {
                node.next = root.next;
                root.next = node;
                size++;
                return;
            }
            root = root.next;
        }
    }

    @Override
    public void add(E value) {
        Node<E> node = new Node<>(value);
        size++;
        if (null == head) {
            head = node;
            return;
        }
        Node root = head;
        while (null != root.next) {
            root = root.next;
        }
        root.next = node;
    }

    @Override
    public boolean delete(E value) {
        if (null == head) {
            throw new IllegalArgumentException("is empty");
        }
        if (head.value == value) {
            size--;
            head = head.next;
            return true;
        }
        Node root = head;
        while (null != root.next) {
            if (root.next.value == value) {
                size--;
                root.next = root.next.next;
                return true;
            }
            root = root.next;
        }
        return false;
    }

    @Override
    public boolean contains(E value) {
        if (null == head) {
            return false;
        }
        Node root = head;
        while (null != root.next) {
            if (root.next.value == value) {
                return true;
            }
            root = root.next;
        }
        return false;
    }

    @Override
    public int getSize() {
        return size;
    }

    public void print() {
        Node root = head;
        while (null != root) {
            System.out.print(root.value + " ");
            root = root.next;
        }
        System.out.println();
    }

    class Node<E> {
        E value;
        Node<E> next;

        public Node(E value) {
            this.value = value;
            this.next = null;
        }
    }

}
